package at.jsug.topicvoting.gwt1.client.view.table;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;

import at.jsug.topicvoting.gwt1.client.logic.event.DeleteVoteEvent;
import at.jsug.topicvoting.gwt1.client.logic.event.SaveVoteEvent;
import at.jsug.topicvoting.gwt1.client.view.table.AbstractTable.ITableColumnModel;
import at.jsug.topicvoting.gwt1.client.vo.Topic;
import at.jsug.topicvoting.gwt1.client.vo.TopicStateDependending;

public class TopicsTableColumnModel implements ITableColumnModel<Topic> {

	private static final List<ITableColumnRenderer<Topic>> COLUMNS;
	static {
		final List<ITableColumnRenderer<Topic>> tmp = new ArrayList<ITableColumnRenderer<Topic>>(2);

		// column == ID ==
		tmp.add(new GridColumnRenderAdapter<Topic>() {
			public String getHeaderText() { return "-ID-"; }
			public String renderAsString(Topic topic) { return String.valueOf(topic.getId()); }
		});

		// column == TITLE ==
		tmp.add(new GridColumnRenderAdapter<Topic>() {
			public String getHeaderText() { return "Title"; }
			public String renderAsString(Topic topic) { return topic.getTitle(); }
		});

		// column == VOTES ==
		tmp.add(new GridColumnRenderAdapter<Topic>() {
			public String getHeaderText() { return "Votes"; }
			public String renderAsString(Topic topic) { return String.valueOf(topic.getVotes()); }
		});

		// column == EXTRA == ... topic state depending
		tmp.add(new GridColumnRenderAdapter<Topic>() {
			public String getHeaderText() { return "-"; }
			public Widget renderAsWidget(final Topic topic) {
				
				final HorizontalPanel extraPanel = new HorizontalPanel();
				
				final boolean yet = topic.isYetVoted();
				final Button btnVote = new Button(yet ? "Revoke" : "Invoke");
				btnVote.addClickListener(new ClickListener() { public void onClick(Widget sender) {
					if(yet) new DeleteVoteEvent(topic).dispatch();
					else new SaveVoteEvent(topic).dispatch();
				}});
				
				topic.getState().dynamicExec(new TopicStateDependending() { // compile time save if-else-cascasdes; nice :)
					public void need() {
						extraPanel.add(btnVote);
					}
					public void offer() {
						extraPanel.add(btnVote);
					}
					public void next() {
						extraPanel.add(btnVote);
					}
					public void past() {
						extraPanel.add(new Label("...past...")); // TODO
					}
				});
				
				return extraPanel;				
			}
			
		});
		
		COLUMNS = Collections.unmodifiableList(tmp);
	}
	
	
	private static final int COLUMNS_LENGTH = COLUMNS.size();
	
	
	public int count() {
		return COLUMNS_LENGTH;
	}

	public ITableColumnRenderer<Topic> get(int index) {
		return COLUMNS.get(index);
	}

}
